package com.webcamtracker.move.tracking;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;


public class ListenersLoader {
    static List<AplicationListener> result;

    public static List<AplicationListener> getListeners() {
        if (result == null) {
            loadListeners();
        }
        return result;
    }

    public static void loadListeners() {
        result = new ArrayList<AplicationListener>();
        try {
            Enumeration<URL> resources = ListenersLoader.class.getClassLoader().getResources("listener.properties");
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                Properties properties = new Properties();
                properties.load(new FileInputStream(new File(url.toURI())));
                Enumeration<String> enumeration = (Enumeration<String>) properties.propertyNames();
                while (enumeration.hasMoreElements()) {
                    String value = enumeration.nextElement();
                    String s = properties.getProperty(value);
                    System.out.println("Loading = " + s);
                    Class<?> aClass = Class.forName(s);
                    Object listener = aClass.newInstance();
                    if (listener instanceof AplicationListener) {
                        result.add((AplicationListener) listener);
                    } else {
                        System.out.println(s + " is not instance of " + AplicationListener.class);
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ListenersLoader().getListeners();
    }

}
